import json
import os
import sys
from module.data.MysqlHelper import MysqlHelper

import logging
log = logging.getLogger("handlelog")

def stockInfo(code, data_date, start_time):
    mysqlHelper = MysqlHelper()
    dataInfo = mysqlHelper.queryStockInfo(code, data_date, start_time)
    log.info("查询股票补充信息 - code:%s datadt:%s %s info:%s" % (code, data_date, start_time, dataInfo))
    return dataInfo

def getTickerRecords(skcode, dateStr, stimeStr, etimeStr):
    startdatetime = "%s %s" % (dateStr, stimeStr)
    enddatetime = "%s %s" % (dateStr, etimeStr)
    mysqlHelper = MysqlHelper()
    tickerData = mysqlHelper.loadTickerData(skcode, startdatetime, enddatetime)
    log.info("加载到逐笔数据: %s" % len(tickerData))
    return tickerData

'''
数据脚本：
#数据导出 2021-08-23 09:30:00   2021-08-23 16:00:00
mysqldump --single-transaction --host=172.16.16.8 -uzhineng1 -pZhineng1! --databases ticker --tables tbl_ticker_us_aapl --where='time >= 1629682200 AND time <= 1629705600' > tbl_ticker_usaapl.log.2021-08-23

#数据导入数据库
mysql -h47.107.245.222 --port 3306 -ulcssxl -pZhongde0-!@# --default-character-set=utf8 -Dticker < tbl_ticker_usaapl.log.2021-08-23
'''
def preTickerHandler(skcode, riqi, stimeStr, etimeStr):
    logDataDate = riqi
    tickerRecordsRaw = getTickerRecords(skcode, logDataDate, stimeStr, etimeStr)

    tickerRecordsNew = []
    if not tickerRecordsRaw:
        return tickerRecordsNew

    index = 0
    recordcnt = 0
    dataLen = len(tickerRecordsRaw)
    while index < dataLen - 1:
        curticker = list(tickerRecordsRaw[index])
        curticker.append(1)
        while index < dataLen - 1:
            if curticker[0] == tickerRecordsRaw[index + 1][0] and curticker[1] == tickerRecordsRaw[index + 1][1]:
                curticker[2] += tickerRecordsRaw[index + 1][2]
                curticker[3] += 1
                index += 1
            else:
                if curticker[2] > 1:
                    log.debug("当前时刻逐笔重复：%s" % curticker)
                break

        if index < dataLen - 1:
            recordcnt += 1
            tickerRecordsNew.append(curticker)

        index += 1
    else:
        if index < dataLen:
            index += 1
            recordcnt += 1
            lastticker = list(tickerRecordsRaw[-1])
            lastticker.append(1)
            tickerRecordsNew.append(lastticker)

    log.info("当前日期逐笔记录数：%s 去重后情况：%s 数据格式：%s" % (dataLen, recordcnt, tickerRecordsNew[-1]))
    return tickerRecordsNew


if __name__ == "__main__":
    skcode = "US.AAPL"
    logDataDate = "2021-08-23"
    starttime = "09:30:00"
    endtime = "16:00:00"

    #preTickerHandler(skcode, logDataDate, starttime, endtime)
    stockInfo(skcode, logDataDate, starttime)


